package com.aoip.telemetry.telemetry.receive.message.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.util.List;

/**
 * 需结合帧解码器使用
 * 解析协议的报文信息（将ByteBuf 转为 字符串格式）
 * 针对报文是16进制格式的编解码器
 *
 * @author chenbai
 * @version 1.0
 * @date 2021/6/15 15:08
 */
@ChannelHandler.Sharable
@Slf4j
public class HexMessageCodecSharable extends MessageToMessageCodec<ByteBuf, String> {

    /**
     * 编码：将字符串转为16进制字符串并写入到消息通道
     *
     * @author chenbai
     * @date 2022/2/28
     **/
    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, List<Object> out) throws DecoderException {
        ByteBuf byteBuf = ctx.alloc().buffer();
        byteBuf.writeBytes(Hex.decodeHex(msg.toCharArray()));
        out.add(byteBuf);
    }

    /**
     * 解码：将接收到的报文转为16进制字符串
     *
     * @author chenbai
     * @date 2022/2/28
     **/
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) {
        int allLength = byteBuf.readableBytes();
        byte[] bytes = new byte[allLength];
        byteBuf.readBytes(bytes, 0, allLength);
        String hexString = Hex.encodeHexString(bytes).toUpperCase();
        log.error("报文：{},localAddress:{}", hexString, ctx.channel().localAddress());
        out.add(hexString);
    }
}
